/**
 * Shift form for AJAX form submit convenience
 * ==================================================
 * Author: lute
 * ==================================================
 * use case:
 * $('form').shiftform({
 *   loadingMessage: '加载提示',    // 可选，默认为“正在提交表单...”
 *   successMessage: '提交成功信息',   // 可选，默认为“表单提交成功”，优先显示服务器返回的成功信息
 *   failureMessage: '提交失败信息',   // 可选，默认为“表单提交失败”，优先显示服务器返回的业务失败信息
 *   errorMessage:  '提交出错信息',   //  可选，默认为“表单提交出错”，表示提交非业务出错信息
 *   beforeSubmit:    function(el) { // 通常做表单校验 },    // 可选，Ajax提交前执行函数
 *   success: function(el, backdrop, message) { // 提交成功callback },    // 可选
 *            string   selector-triggerEvent                            // 可选
 *   failure: function(el, backdrop, message) { // 提交失败callback }    // 可选
 * })
 */

!function(root, factory) {
  if(typeof define == 'function' && define.amd) {
    define(['jquery'], factory)
  } else if(typeof exports == 'object') {
    factory(require('jquery'))
  } else {
    factory(root.jQuery)
  }
}(this, function($) {
  'use strict';

  $.fn.bodyform = function(option) {

    var options = $.extend({
      showModal: true,
      loadingMessage: '正在提交表单...',
      successMessage: '表单提交成功',
      failureMessage: '表单提交失败',
      errorMessage: '表单提交出错',
      beforeSubmit: null,
      success: null,
      failure: null,
    },option)

    var backdrop = '<div class="modal bodyform-modal fade" id="bodyFormModal" tabindex="-1" role="dialog">' +
                     '<div class="modal-dialog" role="document">' +
                       '<div class="modal-content">' +
                         '<div class="modal-body">'+
                           '<div class="bodyform-backdrop">' +
                             '<div class="backdrop-content">' +
                               '<p><span class="icon icon-loader"></span>' +
                                 options.loadingMessage +
                               '</p>' +
                             '</div>' +
                           '</div>'
                         '</div>'+
                       '</div>'+
                     '</div>'+
                   '</div>'
     var backdropNoData = '<div class="modal bodyform-modal fade" id="bodyFormModal" tabindex="-1" role="dialog">' +
                            '<div class="modal-dialog" role="document">' +
                            '</div>'
                          '</div>'

    function checkForm(el) {
      
      if(el.tagName.toUpperCase() != 'FORM') return
      
      var $form = $(el)
      var $body = $("body");
      
      var startSubmit = function(e) {
        e.preventDefault()
        if(e.target != e.currentTarget) return
        if(!options.beforeSubmit || options.beforeSubmit.call(this, el)) {

          // serialize parameters
          var parameters = $form.serializeArray()

          // disable submit button
          $(e.target).attr('disabled', 'disabled')

          // display backdrop first
          if(options.showModal) {
            var $backdrop = $(backdrop).appendTo($body)
            $('#bodyFormModal').modal('show')
          } else {
            var $backdrop = $(backdropNoData).appendTo($body)
            $('#bodyFormModal').modal('show')
          }

          // function for changing backdrop display mesage
          var changeBackdropMessage = function(message, clazz, callback, url) {
            $backdrop.find('p').html('<strong>' + message + '</strong>').addClass(clazz ? clazz : '')
            
            console.log(typeof callback)
            
            if(callback && (typeof callback === 'object' || typeof callback === 'function') ) {
              
              callback(el, $backdrop[0], message)
              setTimeout(function() {
                if($form.data("redirect")){
                  window.location.href = $form.data("redirect");
                }else if(url) {
                  window.location.href = window.__CTX__.root + url;
                } else {
                  window.location.reload() 
                }
              }, 1500)
              
            } else if(callback && typeof callback === 'string') {
                $($form.parents(".modal")).modal('hide');
                $(callback.split('-')[0]).trigger(callback.split('-')[1]);
            }else {
              setTimeout(function() {
                if($form.data("redirect")){
                  window.location.href = $form.data("redirect");
                } else if(url) {
                  window.location.href = window.__CTX__.root + url;
                } else {
                  window.location.reload() 
                }
              }, 1500)
            }
          }
          
          $('#bodyFormModal').on('shown.bs.modal', function (e) {
            $.ajax({
              type: $form.attr('method'),
              url: $form.attr('action'),
              data: parameters
            }).done(function(data) {
              data = typeof data === 'string' ? JSON.parse(data) : data
              if(parseInt(data.code) == 0) {  
                changeBackdropMessage(data.message || options.successMessage, 'text-success', options.success, data.data.url)
              } else {
                changeBackdropMessage(data.message || options.failureMessage, 'text-danger', options.failure, data.data.url)
              }
            }).fail(function() {
              changeBackdropMessage(options.errorMessage, 'text-danger', data.url)
            })
          })
        }
      }

      $form.on('click', '[type="submit"]', startSubmit)
      
      $form.on('click', '[data-shift-submit="true"]', startSubmit)
      
    }

    return this.each(function() {
      checkForm(this)
    })

  }

  $.fn.bodyform.noConflict = function() {
    $.fn.bodyform = old
    return this
  }

})
